package com.example.springflowable.ask_for_leave.controller;

import com.alibaba.fastjson.JSONObject;
import com.example.springflowable.ask_for_leave.service.AskLeaveTaskService;
import com.example.springflowable.common.Results;
import io.swagger.annotations.ApiOperation;
import org.flowable.bpmn.model.BpmnModel;
import org.flowable.engine.*;
import org.flowable.engine.repository.ProcessDefinition;

import org.flowable.engine.runtime.Execution;
import org.flowable.engine.runtime.ProcessInstance;
import org.flowable.engine.task.Comment;
import org.flowable.image.ProcessDiagramGenerator;
import org.flowable.task.api.Task;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.*;

/**
 * @Classname AskLeaveController
 * @Description TODO
 * @Date 2022/5/6 11:55
 * @Created by XiongXiong
 * @Author: X.I.O
 */
@RestController
public class AskLeaveController {

    Logger logger= LoggerFactory.getLogger(AskLeaveController.class);

    @Autowired
    RuntimeService runtimeService;

    @Autowired
    TaskService taskService;

    @Autowired
    RepositoryService repositoryService;

    @Autowired
    ProcessEngine processEngine;

    @Autowired
    AskLeaveTaskService askLeaveTaskService;

    @ApiOperation("查询已经部署的流程定义")
    @GetMapping("getallprocess")
    public JSONObject getAllProcess(){
        List<ProcessDefinition> list = repositoryService.createProcessDefinitionQuery().list();
        for (ProcessDefinition processDefinition : list) {
            System.out.println("processDefinition id ==> "+ processDefinition.getId());
            System.out.println("processDefinition ==> "+processDefinition.getId()+" , "+processDefinition.getName()+"  key:"+ processDefinition.getKey());
        }
        return Results.success(list);
    }

    @ApiOperation("查询审批信息")
    @GetMapping("getmessage")
    public JSONObject getMessage(@RequestParam("processid")String processInstanceId){
        List<Comment> list = taskService.getProcessInstanceComments(processInstanceId);
        return Results.success(list);
    }

    /**
     * 创建任务
     */
    @ApiOperation("创建任务")
    @GetMapping("/create")
    public void createTask(){
        askLeaveTaskService.startTaskAskForLeave();
    }

    @ApiOperation("获取用户的待办")
    @GetMapping("db")
    public JSONObject getDb(@RequestParam("uid")String uid){
        List<Task> tasks = taskService.createTaskQuery()
                .taskCandidateOrAssigned(uid)
                .list();
        if (!tasks.isEmpty()) {
            List<Map<String, Object>> list = new ArrayList<>();
            for (Task task : tasks) {
                Map<String, Object> map = new HashMap<>();
                //代办id
                String taskId = task.getId();
                //代办节点名称
                String taskName = task.getName();
                //创建时间
                Date createTime = task.getCreateTime();


                map.put("taskId", taskId);
                map.put("taskName", taskName);
                map.put("createTime", createTime);
                list.add(map);
            }
            return Results.success(list);
        }
        return Results.success("暂无待办");
    }
    /**
     * 任务提交给组长
     */
    @ApiOperation("任务提交给组长")
    @GetMapping("/submit")
    public void submitTask(){
        askLeaveTaskService.submitToZuzhang();
    }

    @ApiOperation("组长审核通过")
    @GetMapping("submitmanager")
    public void submitManager(){
        askLeaveTaskService.zuZhangApprove();
    }

    @ApiOperation("组长拒绝")
    @GetMapping("zuzhangjujue")
    public void  zuZhangJujue(){
        askLeaveTaskService.zuZhangReject();
    }

    @ApiOperation("经理审核通过")
    @GetMapping("jinglisussess")
    public void jingliSubmitSuccess(){
        askLeaveTaskService.managerApprove();
    }

    @ApiOperation("经理审核拒绝")
    @GetMapping("jinglifail")
    public void jingliJujue(){
        askLeaveTaskService.managerReject();
    }

    @GetMapping("all")
    public void allTasks(){
        //查询所有任务
        List<Task> list = taskService.createTaskQuery().orderByTaskId().desc().list();
        for (Task task : list) {
            logger.info("任务 ID：{}；任务处理人：{}；任务是否挂起：{}; 任务标题: {}", task.getId(), task.getAssignee(), task.isSuspended(),task.getName());
            ProcessInstance processInstance = runtimeService.createProcessInstanceQuery().processInstanceId(task.getProcessInstanceId()).singleResult();

            System.out.println(processInstance.getName()+"实例名称");
        }
    }



    @GetMapping("/pic")
    public void showPic(HttpServletResponse resp, String processId) throws Exception {
        ProcessInstance pi = runtimeService.createProcessInstanceQuery().processInstanceId(processId).singleResult();
        if (pi == null) {
            return;
        }
        List<Execution> executions = runtimeService
                .createExecutionQuery()
                .processInstanceId(processId)
                .list();

        List<String> activityIds = new ArrayList<>();
        List<String> flows = new ArrayList<>();
        for (Execution exe : executions) {
            List<String> ids = runtimeService.getActiveActivityIds(exe.getId());
            activityIds.addAll(ids);
        }

        /**
         * 生成流程图
         */
        BpmnModel bpmnModel = repositoryService.getBpmnModel(pi.getProcessDefinitionId());
        ProcessEngineConfiguration engconf = processEngine.getProcessEngineConfiguration();
        ProcessDiagramGenerator diagramGenerator = engconf.getProcessDiagramGenerator();
        InputStream in = diagramGenerator.generateDiagram(bpmnModel, "png", activityIds, flows, engconf.getActivityFontName(), engconf.getLabelFontName(), engconf.getAnnotationFontName(), engconf.getClassLoader(), 1.0, false);
        OutputStream out = null;
        byte[] buf = new byte[1024];
        int legth = 0;
        try {
            out = resp.getOutputStream();
            while ((legth = in.read(buf)) != -1) {
                out.write(buf, 0, legth);
            }
        } finally {
            if (in != null) {
                in.close();
            }
            if (out != null) {
                out.close();
            }
        }
    }







}
